<template>
  <div class="handle-box">
    <el-dialog
        v-model="handleDialogVisible"
        title="流程详情"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        draggable
        style="
        height: auto;
        background-color:#fff;
        overflow-y: scroll;"
        top="8vh"
    >
      <div class="leave-detail-box">
        <div class="top">
          <div class="t1">
            <div class="t1-item">
              <div class="t1-title">凭证编号</div>
              <div class="t1-con">{{ detail_form.bill_no }}</div>
            </div>
            <div class="t1-item">
              <div class="t1-title">原始单据日期</div>
              <div class="t1-con">{{ computeDate(detail_form.bill_date) }}</div>
            </div>
          </div>
          <div class="t2" style="border-bottom: 1px solid rgb(238,238,238);">
            <div class="t2-item">
              <div class="t2-title">关联项目</div>
              <div class="t2-con">{{ detail_form.related_project_name }}</div>
            </div>
          </div>
          <div class="t1">
            <div class="t1-item">
              <div class="t1-title">报销人</div>
              <div class="t1-con">{{ detail_form.flow_uploader_name }}</div>
            </div>
            <div class="t1-item">
              <div class="t1-title">总费用金额(元)</div>
              <div class="t1-con">
                <div class="t1-con">{{ detail_form.total_money }}</div>
              </div>
            </div>
          </div>
          <div class="t2" style="height: auto">
            <div class="t2-item">
              <div class="t2-title">费用金额</div>
              <div class="t1-con" style="width: 80%;padding: 1vh 1vw; box-sizing: border-box; margin: 0 auto">
                <el-table :data="billItems" border style="width: 95%">
                  <el-table-column prop="sum" label="金额(元)" width="200"  align="center"/>
                  <el-table-column prop="type" label="类型" width="200"  align="center">
                    <template #default = {row}>
                      <el-tag v-if="row.type === '0'">交通费用</el-tag>
                      <el-tag v-if="row.type === '1'">住宿费用</el-tag>
                      <el-tag v-if="row.type === '2'">餐补费用</el-tag>
                      <el-tag v-if="row.type === '3'">招待费用</el-tag>
                      <el-tag v-if="row.type === '4'">汽油费用</el-tag>
                      <el-tag v-if="row.type === '5'">其他费用</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="detail" label="备注"  align="center"/>
                </el-table>
              </div>
            </div>
          </div>
          <div class="t2" style="border-bottom: 1px solid rgb(238,238,238);">
            <div class="t2-item" style="border-top: 1px solid rgb(238, 238, 238);">
              <div class="t2-title">附件</div>
              <div class="t2-con">
                <el-button @click="downloadAccessory">
                  下载附件
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="bot">
          <div class="no-border" v-if="isFormShow">
            <div class="form-box" v-if="detail_form.status !== 2">
              <div class="form-item">
                <div class="title">
                  审批节点
                </div>
                <div class="input">
                  <el-select
                      v-model="submit_form.hasNext"
                      placeholder="请选择审批节点，是否还有下一审批人"
                      size="large"
                      style="width: 99%;height: 4.5vh"
                  >
                    <el-option
                        v-for="item in hasNextOption"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </div>
              </div>
              <div class="form-item next"
                   style="height: 6vh;
             line-height: 6vh"
                   v-if="isNextShow"
              >
                <div class="title">
                  选择下一审批人
                </div>
                <div class="input">
                  <el-cascader v-model="submit_form.nextOperator" :options="options" placeholder="请选择下一审批人"/>
                </div>
              </div>
              <div class="form-item" style="height: 10vh;line-height: 10vh">
                <div class="title">
                  审批描述
                </div>
                <div class="input">
                  <el-input
                      v-model="submit_form.reason"
                      style="width: 99%;height: 9.5vh"
                      type="textarea"
                      placeholder="请输入审批描述,不超过70字"
                  />
                </div>
              </div>
              <div class="form-item" style="height: 5.5vh;line-height: 5.5vh">
                <div class="title">
                  审批意见
                </div>
                <div class="input">
                  <el-select
                      v-model="submit_form.result"
                      placeholder="请选择审批结果"
                      size="large"
                      style="width: 99%;height: 4.5vh"
                  >
                    <el-option
                        v-for="item in resultOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </div>
              </div>
            </div>
            <div class="form-submit" v-show="detail_form.status !== 2">
              <el-button type="primary" @click="submitResult">
                提交
              </el-button>
            </div>
          </div>
          <div class="approve-result" v-show="detail_form.status === 2">
            <div class="bot">
              <div class="b1">
                <div class="b1-item">
                  <div class="b1-title">审核状态</div>
                  <div class="b1-con">
                    <div v-if="detail_form.status === 0">已提交</div>
                    <div v-if="detail_form.status === 1">审核中</div>
                    <div v-if="detail_form.status === 2">已完成</div>
                  </div>
                </div>
                <div class="b1-item">
                  <div class="b1-title">当前审核人</div>
                  <div class="b1-con">{{ detail_form.flow_operator_name }}</div>
                </div>
                <div class="b1-item">
                  <div class="b1-title">抄送人</div>
                  <div class="b1-con">
                    {{ detail_form.copy ? detail_form.copy : '无' }}
                  </div>
                </div>
              </div>
              <div class="b2">
                <div class="b2-item">
                  <div class="b2-title">历史审批</div>
                  <div class="b2-con" v-if="history_operator.length">
                    <p v-for="(item,index) in history_operator" :key="index" style="font-weight: 600; color: #1E90FF">
                      {{ item }}&nbsp;
                      <span v-if="!index === historyOperator.length - 1" style="font-weight: 400; color: black">
                    -> &nbsp;
                  </span>
                    </p>
                  </div>
                  <div class="b2-con" v-else>
                    暂无数据
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ElButton,
  ElDialog,
  ElMessage,
  ElInput,
  ElCascader,
  ElTableColumn,
  ElTag, ElTable
} from "element-plus"
import {onMounted, reactive, ref, defineEmits, watch} from "vue"
import {useRoute} from "vue-router"
import {getBillDetails, getFinHandler} from "@/api/Finance/Bill"
import {handleBill} from "@/api/Finance/Bill/index.js"
import {computeDate} from "@/lib/utils"
import {baseurl} from "@/api/http"

const route = useRoute()
const emits = defineEmits(['reloadHandle'])

let user_info
const url = `${baseurl}/downloadAccessory?flowId=`
const submit = `${baseurl}/handleBill`

const handleDialogVisible = ref(false)
const historyOperator = ref([])
const options = ref([])
const rules = {
  node:{},
  next:{},
  reason:{},
  result:{},
}
// const hasNext = ref(true)

const resultOptions = [
  {
    value: 1,
    label: '通过',
  },{
    value: 0,
    label: '拒绝',
  },
]
const hasNextOption = [
  {
    value: 0,
    label: '结束审核',
  },{
    value: 1,
    label: '继续选择下一审批人',
  },
]

const isNextShow = ref(true)
const isFormShow = ref(true)

let currentFlowId

let detail_form = reactive({
  starting_date:'',
  termination_date:'',
  flow_detail:'',
  total_days:'',
  status:'',
  operator_name:'',
  copy_name:'',
})

let submit_form = reactive({
  result:null,
  reason:null,
  nextOperator:[],
  flowId:'',
  hasNext:null,
  userId:'',
})

const history_operator = ref([])
const billItems = ref([])
onMounted(() => {
  if(route.path === '/handled'){
    hasNext.value = false
    isFormShow.value = false
  }
  getUserInfo()
  getUserList()
})

const getUserInfo = () => {
  user_info = JSON.parse(localStorage.getItem('syhyDocManSys'))
}

const getUserList = async () => {
  try {
    let rolename = []
    let roleUser = []
    const {data:res} = await getFinHandler()
    const values = Object.values(res.data)
    values.forEach(value => {
      let datas = Object.values(value)
      datas.forEach(data => {
        if(typeof data === "string"){
          rolename.push(data)
        } else {
          roleUser.push(data)
        }
      })
    })
    for (let i = 0; i < 3; i++){
      options.value.push({
        label:rolename[i],
        value:null,
        children:[]
      })
      for (let j = 0; j < roleUser[i].length; j++){
        options.value[i].children.push({
              label:roleUser[i][j].user_name,
              value:roleUser[i][j].user_id,
            }
        )
      }
    }
  } catch (e) {
    console.log(e)
  }
}

const showDetails = async (id) => {
  try {
    currentFlowId = id
    const {data:res} = await getBillDetails({
      projectId:id
    })
    if(res.code === 200){
      detail_form = res.data.data
      handleDialogVisible.value = true
      for (let i = 0; i < res.data.history.length; i++){
        history_operator.value.push(res.data.history[i])
      }
      billItems.value = JSON.parse(res.data.data.finance_items)
    } else {
      ElMessage({
        message:'获取失败',
        type:'error'
      })
    }
  } catch (e) {
    console.log(e)
  }
}

const submitResult = async () => {
  try {
    const form = new FormData();
    form.append("flowId", currentFlowId);
    form.append("hasNext", submit_form.hasNext);
    form.append("nextOperator", submit_form.hasNext === 0 ? null : submit_form.nextOperator[submit_form.nextOperator.length - 1]);
    form.append("reason", submit_form.reason);
    form.append("result", submit_form.result);
    form.append("operator", user_info.id);

    //region
    // const options = {
    //   method: 'POST',
    //   url: submit,
    //   data: form
    // };
    //
    // axios.request(options).then(function (res) {
    //   if(res.data.code === 200){
    //     submit_form = {
    //       result:null,
    //       reason:null,
    //       nextOperator:null,
    //       flowId:'',
    //       hasNext:null,
    //       userId:'',
    //     }
    //     if(route.path === '/all-handle'){
    //       emits('reloadAll')
    //     } else if (route.path === '/to-handle'){
    //       emits('reloadHandle')
    //     }
    //     handleDialogVisible.value = false
    //     return ElMessage({
    //       message:'操作成功!',
    //       type:'success'
    //     })
    //   } else {
    //     return ElMessage({
    //       message: '操作失败!',
    //       type: 'warning'
    //     })
    //   }
    // }).catch(function (error) {
    //   console.error(error);
    // });
    //endregion

    const obj = {
      flowId:currentFlowId,
      hasNext:submit_form.hasNext,
      nextOperator:submit_form.hasNext === 1 ? submit_form.nextOperator[submit_form.nextOperator.length-1] : null,
      reason:submit_form.reason,
      result:submit_form.result,
      operator:user_info.id,
    }

    const {data: res} = await handleBill(obj)
    if(res.code === 200){
      submit_form.result = null
      submit_form.reason = null
      submit_form.nextOperator = []
      submit_form.flowId = ''
      submit_form.hasNext = null
      submit_form.userId = ''

      handleDialogVisible.value = false
      emits('reloadHandle')
      return ElMessage({
        message:'操作成功!',
        type:'success'
      })
    } else {
      return ElMessage({
        message:'操作失败!',
        type:'warning'
      })
    }
  } catch (e) {
    console.log(e)
  }
}
  //region
  // const {data:res} = await handleBill({
  //   result:submit_form.result, // result
  //   reason:submit_form.reason, // reason
  //   nextOperator:submit_form.hasNext ? submit_form.nextOperator[submit_form.nextOperator.length-1] :null, // $nextOperator
  //   flowId:currentFlowId, // flowId
  //   hasNext:submit_form.hasNext, // hasNext
  //   operator:user_info.id, // operator
  // })
  // try {
  //   if (submit_form.result !== 0 && submit_form.result !== 1){
  //     return ElMessage({
  //       message:'审批结果不能为空!',
  //       type:'error'
  //     })
  //   } else if (submit_form.hasNext === 1 && !submit_form.nextOperator){
  //     return ElMessage({
  //       message:'请选择下一个审批人!',
  //       type:'error'
  //     })
  //   } else {
  //     const {data:res} = await handleBill({
  //       result:submit_form.result, // result
  //       reason:submit_form.reason, // reason
  //       nextOperator:submit_form.hasNext ? submit_form.nextOperator[submit_form.nextOperator.length-1] :null, // $nextOperator
  //       flowId:currentFlowId, // flowId
  //       hasNext:submit_form.hasNext, // hasNext
  //       operator:user_info.id, // operator
  //     })
  //     if(res.code === 200){
  //       submit_form = {
  //         result:null,
  //         reason:null,
  //         nextOperator:null,
  //         flowId:'',
  //         hasNext:null,
  //         userId:'',
  //       }
  //       if(route.path === '/all-handle'){
  //         emits('reloadAll')
  //       } else if (route.path === '/to-handle'){
  //         emits('reloadHandle')
  //       }
  //       handleDialogVisible.value = false
  //       return ElMessage({
  //         message:'操作成功!',
  //         type:'success'
  //       })
  //     } else {
  //       return ElMessage({
  //         message:'操作失败!',
  //         type:'warning'
  //       })
  //     }
  //   }
  //
  // } catch (e) {
  //   console.log(e)
  // }
// }
//endregion

const isLastItem = (index) => {
  return index === historyOperator.value.length - 1;
}

const handleClose = () => {
  submit_form.result = null
  submit_form.reason = null
  submit_form.nextOperator = null
  submit_form.flowId = ''
  submit_form.hasNext = null
  submit_form.userId = ''

  if(route.path === '/all-handle'){
    emits('reloadAll')
  } else if (route.path === '/to-handle'){
    emits('reloadHandle')
  }
  handleDialogVisible.value = false
}

const downloadAccessory = async () => {
  const link = document.createElement('a')
  link.href = url+currentFlowId
  link.click()
}

watch([()=>submit_form.hasNext,()=>submit_form.result],()=>{
  if (submit_form.hasNext === 0){
    isNextShow.value = false
    submit_form.nextOperator = []
  } else if (submit_form.hasNext === 1 && submit_form.result === 0) {
    ElMessage({
      message:'拒绝该请求后不能再选择下一审批人',
      type:'error'
    })
    // isNextShow.value = true
    // submit_form.result = 1
  }

  if (submit_form.result === 0){
    submit_form.hasNext = 0
    isNextShow.value = false
    submit_form.nextOperator = []
  }
})

watch(()=>submit_form.nextOperator,()=>{
  if (submit_form.nextOperator.length === 1){
    submit_form.nextOperator = []
    ElMessage({
      message:'不能选择部门作为审核人',
      type:'error'
    })
  }
})
defineExpose({
  showDetails,
})
</script>

<style scoped lang="less">
.handle-box{
  box-sizing: border-box;
  height: 95%;
  :deep(.el-dialog__body) {
    padding-top: 0 !important;
  }
  .leave-detail-box{
    width: 95%;
    .top{
      background-color:#fff;
      border: 1px solid rgb(238,238,238);
      display: flex;
      flex-direction: column;
      margin-top: 2vh;
      .t1{
        width: 100%;
        font-size: 1.6vh;
        border-bottom: 1px solid rgb(238,238,238);
        height: 5vh;
        line-height: 5vh;
        display: flex;
        justify-content: space-between;
        .t1-item{
          width: 100%;
          display: flex;
          justify-content: left;
          .t1-title{
            font-weight: 600;
            text-align: center;
            width: 30%;
            background-color: rgb(250,250,250);
            border-left: 1px solid rgb(250,250,250);
            border-right: 1px solid rgb(250,250,250);
          }
          .t1-con{
            text-align: left;
            background-color: #fff;
            width: 60%;
            padding-left: 1vw;
          }
        }
      }
      .t2{
        width: 100%;
        font-size: 1.6vh;
        background-color:#fff;
        height: 5vh;
        line-height: 5vh;
        display: flex;
        .t2-item{
          width: 100%;
          display: flex;
          justify-content: left;
          .t2-title{
            font-weight: 600;
            text-align: center;
            width: 15%;
            background-color: rgb(250,250,250);
            border-left: 1px solid rgb(250,250,250);
            border-right: 1px solid rgb(250,250,250);
          }
          .t2-con{
            text-align: left;
            background-color: #fff;
            width: 60%;
            padding-left: 1vw;
          }
        }
      }
    }
    .bot{
      .no-border{
        .form-box{
          display: flex;
          flex-direction: column;
          background-color: #fff;
          border: 1px solid #eeeeff;
          border-bottom: none;
          width: 100%;
          margin: 0 auto;
          margin-top: 2vh;
          .form-item{
            display: flex;
            justify-content: left;
            height: auto;
            border-bottom: 1px solid rgb(238, 238, 238);
            font-size: 1.6vh;
            .title{
              width: 15%;
              text-align: center;
              border-right: 1px solid rgb(238, 238, 238);
              background-color: rgb(250, 250, 250);
              font-weight: 600;
            }
            .input{
              width: 85%;
              text-align: left;
              padding-left: 1vw;
            }
          }
        }
        .form-submit{
          margin: 2vh auto 0 auto;
          border: none;
          width: 95%;
          text-align: right;
        }
      }
    }
  }
}
.approve-result{
  .bot{
    background-color:#fff;
    border: 1px solid rgb(238,238,238);
    //border-left: none;
    margin-top: 3vh;
    display: flex;
    flex-direction: column;
    .b1{
      display: flex;
      width: 100%;
      font-size: 1.6vh;
      border-bottom: 1px solid rgb(238,238,238);
      height: 5vh;
      line-height: 5vh;
      .b1-item{
        width: 100%;
        display: flex;
        justify-content: left;
        .b1-title{
          font-weight: 600;
          text-align: center;
          width: 49%;
          background-color: rgb(250,250,250);
          border-left: 1px solid rgb(250,250,250);
          border-right: 1px solid rgb(250,250,250);
        }
        .b1-con{
          text-align: left;
          background-color: #fff;
          width: 60%;
          padding-left: 1vw;
        }
      }
    }
    .b2{
      background-color:#fff;
      width: 100%;
      font-size: 1.6vh;
      height: 5vh;
      line-height: 5vh;
      display: flex;
      .b2-item{
        width: 100%;
        display: flex;
        justify-content: left;
        .b2-title{
          font-weight: 600;
          text-align: center;
          width: 14%;
          background-color: rgb(250,250,250);
          border-left: 1px solid rgb(250,250,250);
          border-right: 1px solid rgb(250,250,250);
        }
        .b2-con{
          text-align: left;
          background-color: #fff;
          width: 60%;
          padding-left: 1vw;
          display: flex;
          line-height: 5vh;
          align-items: center;
        }
      }
    }
  }
}
</style>
